
#import "AppController.h"
#import <Cocoa/Cocoa.h>
#import <Quartz/Quartz.h>
#import <ObjectiveFlickr/ObjectiveFlickr.h>

#define kSlideShowInterval			3.0


@implementation AppController

NSMutableArray*				_fileList;
NSOpenGLContext*			_openGLContext;
QCRenderer*					_renderer;

OFFlickrAPIContext *flickrContext;
OFFlickrAPIRequest *flickrRequest;
NSMutableArray*					urls;

- (id) init
{
    if(self = [super init])
		[self setDelegate:self];
    
    return self;
}


- (void)dealloc
{
	[flickrContext release];
	[flickrRequest release];
	[super dealloc];
}

- (void) awakeFromNib
{
	NSArray*						imageFileTypes = [NSImage imageFileTypes];
	
	flickrContext = [[OFFlickrAPIContext alloc] initWithAPIKey:@"a3a1816160df276820a3ae41f8959bc1" sharedSecret:@"627f9645f22ef0c6"];
	flickrRequest = [[OFFlickrAPIRequest alloc] initWithAPIContext:flickrContext];
	[flickrRequest setDelegate:self];
	
	
	

}

- (void) _performTransition:(id)param
{
	
	
	NSLog(@"Performtransition");
	
	double                    time;
    NSImage*                image;
	
	image = [[NSImage alloc] initWithContentsOfURL:[urls objectAtIndex:0]];
	if(image == nil)
		NSLog(@"Cannot load image file at path: %@", [_fileList objectAtIndex:0]);

	[urls removeObjectAtIndex:0];
	
	
	
	[_renderer setValue:[_renderer valueForInputKey:@"destination"] forInputKey:@"source"];
	[_renderer setValue:image forInputKey:@"destination"];
	
	[image release];
	
	for(time = 0.0; time < 1.0; time += 0.01) {
		if(![_renderer renderAtTime:time arguments:nil])
			NSLog(@"Rendering failed at time %.3fs", time);
		[_openGLContext flushBuffer];
	}
	
	if(![_renderer renderAtTime:1.0 arguments:nil]) 		NSLog(@"Rendering failed at time %.3fs", time);
	[_openGLContext flushBuffer];
	
	if ([urls count])
	[self performSelector:@selector(_performTransition:) withObject:nil afterDelay:kSlideShowInterval];
	
}

- (void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest didCompleteWithResponse:(NSDictionary *)inResponseDictionary
{
	double					time;
	NSImage					*image;
	GLint					value = 1;

	NSLog(@"flickrAPIRequest");
	
	NSArray *photos = [inResponseDictionary valueForKeyPath:@"photos.photo"];
	
	urls = [NSMutableArray new];
	
	for (NSDictionary *photo in photos) {
		[urls addObject:[inRequest.context photoSourceURLFromDictionary:photo size:OFFlickrMediumSize]];
	}	

    if ([urls count] < 2) {
        NSLog(@"The directory contain less than 2 image files");
        [NSApp terminate:nil];
    }
	
	CGDisplayCapture(kCGDirectMainDisplay);
	CGDisplayHideCursor(kCGDirectMainDisplay);
	
	NSOpenGLPixelFormatAttribute	attributes[] = {
		NSOpenGLPFAFullScreen,
		NSOpenGLPFAScreenMask, CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay),
		NSOpenGLPFANoRecovery,
		NSOpenGLPFADoubleBuffer,
		NSOpenGLPFAAccelerated,
		NSOpenGLPFADepthSize, 24,
		(NSOpenGLPixelFormatAttribute) 0
	};
	
	
	NSOpenGLPixelFormat*			format = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attributes] autorelease];
	
	_openGLContext = [[NSOpenGLContext alloc] initWithFormat:format shareContext:nil];
	if(_openGLContext == nil) {
		NSLog(@"Cannot create OpenGL context");
		[NSApp terminate:nil];
	}
	[_openGLContext setFullScreen];
	[_openGLContext setValues:&value forParameter:kCGLCPSwapInterval];
	
	_renderer = [[QCRenderer alloc] initWithOpenGLContext:_openGLContext pixelFormat:format file:[[NSBundle mainBundle] pathForResource:@"Transition" ofType:@"qtz"]];
	if(_renderer == nil) {
		NSLog(@"Cannot create QCRenderer");
		[NSApp terminate:nil];
	}
	
	
	[self performSelector:@selector(_performTransition:) withObject:nil afterDelay:kSlideShowInterval];
	
}

- (void) sendEvent:(NSEvent*)event
{
	if(([event type] == NSKeyDown) && ([event keyCode] == 0x35))
	[NSApp terminate:nil];
	
	[super sendEvent:event];
}

- (IBAction) runSlideShow: (id) sender {
	[window setIsVisible:FALSE];
	 [flickrRequest callAPIMethodWithGET:@"flickr.photos.search" arguments:[NSDictionary dictionaryWithObjectsAndKeys:[tags stringValue], @"tags", @"interestingness-desc", @"sort", @"1", @"content_type", @"500", @"per_page", nil]];

}

- (void) applicationWillTerminate:(NSNotification*)aNotification 
{
	[_renderer release];
	
	[_openGLContext clearDrawable];
	[_openGLContext release];
	
	if(CGDisplayIsCaptured(kCGDirectMainDisplay)) {
		CGDisplayShowCursor(kCGDirectMainDisplay);
		CGDisplayRelease(kCGDirectMainDisplay);
	}
	
	[urls release];
}

@end

int main(int argc, const char *argv[])
{
    return NSApplicationMain(argc, argv);
}
